<template>
  <section class="integral-config">
    <section v-for="(item, i) in group" :key="i" class="set-card">
      <el-collapse accordion>
        <el-collapse-item>
          <template slot="title">
            <div class="myTitle">{{ item.name }}</div>
          </template>
          <section class="card-inner">
            <el-form label-width="320px" :label-position="labelPosition">
              <el-form-item v-for="(ite, j) in item.list" :key="j" :label="ite.name">
                <el-input
                  v-model.trim="ite.value"
                  onkeyup="value=value.replace(/[^-.\d]/g,'')"
                  :placeholder="`请输入${ite.error ? ite.error : ite.name}`"
                  style="width: 40%"
                />
                <el-button :loading="ite.loadingBtn" type="primary" style="margin-left: 10px" @click="handleComit(ite)">
                  确 定
                </el-button>
                <el-tag size="mini" style="margin-left: 30px">{{
                  ite.nameTime ? '上次设置时间：' + ite.nameTime : '未设置'
                }}
                </el-tag>
              </el-form-item>
            </el-form>
          </section>
        </el-collapse-item>
      </el-collapse>
    </section>
    <section class="set-card">
      <el-collapse accordion>
        <el-collapse-item>
          <template slot="title">
            {{ pageData.MODULE_GET_INTEGRAL_RULE.name }}
            <el-tag
              size="mini"
            >{{
              pageData.MODULE_GET_INTEGRAL_RULE.updTime
                ? '上次设置时间：' + pageData.MODULE_GET_INTEGRAL_RULE.updTime
                : '未设置'
            }}
            </el-tag>
          </template>
          <section class="card-inner">
            <el-button style="float: right; margin-bottom: 10px;" class="add" @click="addCustomIntegral">添加</el-button>
            <el-table :data="pageData.MODULE_GET_INTEGRAL_RULE.configValue" stripe style="width: 100%">
              <el-table-column prop="name" label="标识">
                <template slot-scope="scope">
                  <el-input v-model.trim="scope.row.name" />
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="名称">
                <template slot-scope="scope">
                  <el-input v-model.trim="scope.row.remark" />
                </template>
              </el-table-column>
              <el-table-column prop="isLogin" width="150" label="是否需要登录">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.isLogin"
                    active-value="yes"
                    active-text="需要"
                    inactive-text="不需要"
                    inactive-value="no"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="isGetPoints" width="150" label="是否可获得积分">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.isGetPoints"
                    active-value="yes"
                    active-text="可以"
                    inactive-text="不可以"
                    inactive-value="no"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="type" label="类型">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.type" placeholder="请选择">
                    <el-option label="根据时长" value="1" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="learnDuration" label="获得积分的学习时长（单位：秒）">
                <template slot-scope="scope">
                  <el-input v-model.trim="scope.row.learnDuration" onkeyup="value=value.replace(/[^-.\d]/g,'')" />
                </template>
              </el-table-column>
              <el-table-column prop="learnPoints" label="达到指定时长获得积分">
                <template slot-scope="scope">
                  <el-input v-model.trim="scope.row.learnPoints" onkeyup="value=value.replace(/[^-.\d]/g,'')" />
                </template>
              </el-table-column>
              <el-table-column prop="erverydayMaxPoints" label="获得积分每日上限（-1：不限制）">
                <template slot-scope="scope">
                  <el-input v-model.trim="scope.row.erverydayMaxPoints" onkeyup="value=value.replace(/[^-.\d]/g,'')" />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="60" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button type="text" size="mini" @click="pageData.MODULE_GET_INTEGRAL_RULE.configValue.splice(scope.$index, 1)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button
              :loading="pageData.MODULE_GET_INTEGRAL_RULE.loading"
              style="display: block; margin: 10px auto"
              type="primary"
              @click="handleSubmit('MODULE_GET_INTEGRAL_RULE')"
            >确 定
            </el-button>
          </section>
        </el-collapse-item>
      </el-collapse>
    </section>
  </section>
</template>
<script>
import { getDataByType, setDataByType } from './api'

export default {
  name: 'IntegralConfig',
  data() {
    return {
      loadingBtn: false,
      labelPosition: 'left',
      group: [
        {
          name: '课程学习积分配置',
          list: [
            {
              code: 'LEARN_SUBJECT_DURATION',
              name: '课程学习获得积分的学习时长（单位：秒）',
              error: '课程学习获得积分的学习时长',
              type: 'num',
              value: '',
              nameTime: '',
              loadingBtn: false
            },
            {
              code: 'LEARN_SUBJECT_POINTS',
              name: '课程学习达到指定时长获得积分',
              error: '课程学习达到指定时长获得积分',
              type: 'num',
              value: '',
              nameTime: '',
              loadingBtn: false
            },
            {
              code: 'LEARN_SUBJECT_MAX_SCORE',
              name: '课程学习获得积分每日上限（-1：不限制）',
              type: 'num',
              value: '',
              nameTime: '',
              loadingBtn: false
            }
          ]
        },
        {
          name: '闯关积分配置',
          list: [
            {
              code: 'LEARN_SUCC_POINTS',
              name: '每次闯关成功获得积分',
              type: 'num',
              value: '',
              nameTime: '',
              loadingBtn: false
            },
            {
              code: 'LEARN_FAIL_POINTS',
              name: '每次闯关失败获得积分',
              type: 'num',
              value: '',
              nameTime: '',
              loadingBtn: false
            },
            {
              code: 'LEARN_EVERYDAY_MAX_SCORE',
              name: '每日闯关获得积分上限（-1：不限制）',
              error: '每日闯关获得积分上限',
              type: 'num',
              value: '',
              nameTime: '',
              loadingBtn: false
            }
          ]
        },
        {
          name: '专项答题积分配置',
          list: [
            {
              code: 'ACTIVITY_SUCC_POINTS',
              name: '每次专项答题成功获得积分',
              type: 'num',
              value: '',
              nameTime: '',
              loadingBtn: false
            },
            {
              code: 'ACTIVITY_FAIL_POINTS',
              name: '每次专项答题失败获得积分',
              type: 'num',
              value: '',
              nameTime: '',
              loadingBtn: false
            },
            {
              code: 'ACTIVITY_EVERYDAY_MAX_SCORE',
              name: '每日专项答题获得积分上限（-1：不限制）',
              error: '每日专项答题获得积分上限',
              type: 'num',
              value: '',
              nameTime: '',
              loadingBtn: false
            }
          ]
        }
      ],
      pageData: {
        MODULE_GET_INTEGRAL_RULE: {
          name: '自定义积分规则配置',
          loading: false,
          updTime: '',
          configValue: [{
            'name': 'warmtransceiver',
            'remark': '温暖电台',
            'learnDuration': '10',
            'learnPoints': '5',
            'erverydayMaxPoints': '10',
            'isLogin': 'yes',
            'isGetPoints': 'yes'
          }, {
            'name': 'bookstore',
            'remark': '工匠书坊',
            'isLogin': 'no',
            'isGetPoints': 'no'
          },
          { 'name': 'exhibitionCenter', 'remark': '线上云展馆', 'isLogin': 'no', 'isGetPoints': 'no' }]
        }
      }

    }
  },
  async created() {
    const loading = this.$loading({
      lock: true,
      text: '请稍后...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    this.group.forEach(element => {
      element.list.forEach(e => {
        this.getSystemData(e)
      })
    })
    for (const i in this.pageData) {
      await this.getConfigData(i)
    }
    loading.close()
  },
  methods: {
    handleComit(ite) {
      if (!ite.value) {
        return this.$message.error(`请输入${ite.error ? ite.error : ite.name} `)
      }
      ite.loadingBtn = true
      return new Promise((resolve, reject) => {
        setDataByType({ configName: ite.code, configValue: ite.value }).then((res) => {
          ite.loadingBtn = false
          this.$message({
            title: '成功',
            message: '设置成功',
            type: 'success',
            duration: 1500
          })
          this.getSystemData(ite)
        }).catch(error => {
          ite.loadingBtn = false
          reject(error)
        })
      })
    },
    getSystemData(item) {
      return new Promise((resolve, reject) => {
        getDataByType({ name: item.code }).then((res) => {
          item.value = res.data.data.configValue || ''
          item.nameTime = res.data.data.updTime || ''
        }).catch(error => {
          reject(error)
        })
      })
    },
    addCustomIntegral() {
      this.pageData.MODULE_GET_INTEGRAL_RULE.configValue.push({
        name: '',
        remark: '',
        learnDuration: '',
        learnPoints: '',
        erverydayMaxPoints: '',
        isLogin: 'no',
        isGetPoints: 'yes'
      })
    },
    getConfigData(code) {
      return new Promise((resolve, reject) => {
        getDataByType({ name: code }).then((res) => {
          this.pageData[code].updTime = res.data.data.updTime || ''
          if (code === 'MODULE_GET_INTEGRAL_RULE') {
            try {
              this.pageData[code].configValue = JSON.parse(res.data.data.configValue)
            } catch (err) {
              console.warn(err)
              this.pageData[code].configValue = []
            }
          }
          resolve()
        }).catch(error => {
          resolve(error)
        })
      })
    },
    handleSubmit(code) {
      return new Promise((resolve, reject) => {
        let configValue = ''
        if (code === 'MODULE_GET_INTEGRAL_RULE') {
          const arr = this.pageData[code].configValue.filter(item => item.name)
          configValue = JSON.stringify(arr)
        }
        this.pageData[code].loading = true
        setDataByType({ configName: code, configValue: configValue }).then((res) => {
          this.pageData[code].loading = false
          this.$message({
            title: '成功',
            message: '设置成功',
            type: 'success',
            duration: 1500
          })
          this.getConfigData(code)
        }).catch(error => {
          this.pageData[code].loading = false
          reject(error)
        })
      })
    }
  }
}
</script>
<style lang="scss">
.integral-config {
  padding: 10px;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;

  .myTitle {
    // background: #000;
    height: 100%;
    width: 100%;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    word-break: break-all;
    // line-height: 30px;
  }

  &::-webkit-scrollbar {
    width: 8px; /*对垂直流动条有效*/
    height: 1px; /*对水平流动条有效*/
  }

  /** 滚动条轨道*/
  &::-webkit-scrollbar-track {
    box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
    background-color: white;
    border-radius: 3px;
  }

  /** 滚动条里面小方块*/
  &::-webkit-scrollbar-thumb {
    height: 32px;
    border-radius: 5px;
    box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.2);
    background-color: #eaeaea;
  }

  &:hover {
    overflow: auto;
  }

  .set-info,
  .set-card {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .el-collapse {
      border-top: none;
      border-bottom: none;

      .el-collapse-item__header {
        padding-left: 10px;
        border-bottom: none;
        overflow: hidden;
        text-overflow: ellipsis;

        .el-tag {
          margin-left: 10px;
        }

        .name {
          flex-shrink: 0;
          white-space: nowrap;
        }
      }

      .el-collapse-item__content {
        padding: 10px;
      }

      .el-collapse-item__wrap {
        border-bottom: none;
        border-top: 1px solid #e6ebf5;
      }
    }
  }

  .set-card {
    margin-top: 10px;
  }

  .set-info {
    .info-item {
      padding-bottom: 8px;
      vertical-align: top;
      display: flex;

      .item-label {
        color: rgba(0, 0, 0, 1);
        font-weight: 400;
        font-size: 14px;
        line-height: 1.5715;
        text-align: start;
      }

      .item-content {
        flex: 1 1;
        color: rgba(0, 0, 0, 0.85);
        font-size: 14px;
        line-height: 1.5715;
        word-break: break-word;
        overflow-wrap: break-word;
      }
    }
  }

  .color-inner {
    display: flex;
    align-items: center;

    .inner-item {
      width: 25px;
      height: 25px;
      margin-right: 8px;
      color: #fff;
      font-size: 20px;
      font-weight: 700;
      border-radius: 2px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;

      > i {
        display: none;
      }

      &.active i {
        display: inline-block;
      }
    }
  }
}
</style>
